package com.example.consumer.dubbo.web;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.alibaba.dubbo.config.annotation.Reference;
import com.example.dubbo.service.StudentService;
import com.example.model.Student;

import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class StudentController {

  @Reference(interfaceClass = StudentService.class, version = "1.0.0", check = false)
  private StudentService studentService;

  @RequestMapping(value = "/springboot/students")
  // @ResponseBody
  public Object student(Integer id) {
    return studentService.queryStudentById(id);
  }

  @RequestMapping(value = "/update/student")
  // @ResponseBody
  public Object update(Integer id, String studentName) {
    Student student = new Student();
    student.setId(id);
    student.setStuName(studentName);
    int modifyCount = studentService.modifyStudentById(student);

    return "修改的结果" + modifyCount;
  }

  // ============== RESTful ==============
  // @GetMapping(value = "/student/detail/{id}")
  // public Object detail1(@PathVariable Integer id) {
  //   return "restful " + id;
  // }

  @DeleteMapping(value = "/student/{id}")
  public Object removeStudent(@PathVariable("id") Integer id) {
    return "删除的学生 id 为：" + id;

  }

  @PutMapping(value = "/student/{id}")
  public Object modifyStudent(@PathVariable("id") Integer id) {
    return "修改学生的 id 为" + id;
  }

  // 即使路径参数类型不同，也会发生路径冲突
  // 1.修改请求路径
  // 2.修改请求方式
  @GetMapping(value = "/student/detail/{name}/{age}")
  public Object detail1(@PathVariable("name") String name, @PathVariable Integer age) {
    Map<String, Object> restMap = new HashMap<>();
    restMap.put("name", name);
    restMap.put("age", age);
    return restMap;
  }

  // ============== Redis ==============
  @GetMapping(value = "/student/allStudentCount")
  public Object allStudentCount() {
    // 模拟并发
    // 定义一个固定的线程池
    ExecutorService executorService = Executors.newFixedThreadPool(100);

    for (int i = 0; i < 1000; i++) {
      // 开启一个线程
      executorService.submit(new Runnable() {
        @Override
        public void run() {
          studentService.queryAllStudentCount();
        }
      });
    }

    Long allStudentCount = studentService.queryAllStudentCount();
    return "学生总数: " + allStudentCount;
  }

}
